package com.fjec.common.rabbitmq;

import com.fjec.common.Const;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

@Slf4j
public class BaseCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    protected String traceId;

    public BaseCallback(String traceId) {
        this.traceId = traceId;
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (!ack) {
            MDC.put(Const.TRACE_ID_KEY, this.traceId);
            log.error("{} fault! ID={}, CAUSE={}", traceId, correlationData, cause);
            MDC.remove(Const.TRACE_ID_KEY);
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText,
                                String exchange, String routingKey) {
        MDC.put(Const.TRACE_ID_KEY, this.traceId);
        log.error("{} return fault! ECH={}, KEY={}, CODE={}, TEXT={}", traceId, exchange, routingKey, replyCode, replyText);
        MDC.remove(Const.TRACE_ID_KEY);
    }

}
